package com.adminserver.controller;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.adminserver.entity.AdminEntity;
import com.adminserver.customEntity.LoginInfoEntity;
import com.adminserver.customEntity.SaltEntity;
import com.adminserver.entity.AdminJobRecordEntity;
import com.adminserver.entity.UserRoleEntity;
import com.adminserver.mapper.AdminJobRecordMapper;
import com.adminserver.service.AdminService;
import com.adminserver.service.UserRoleService;
import com.adminserver.util.rsaUtil.GenerateKey;
import com.adminserver.util.rsaUtil.RsaUtil;
import com.adminserver.util.responseUtil.ResponseEnum;
import com.adminserver.util.responseUtil.ResponseUtil;
import com.adminserver.util.stpInterface.StpInterfaceImpl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@Slf4j
@RestController
@RequestMapping("/login")
public class LoginController {

    @Autowired
    RsaUtil rsaUtil;

    @Autowired
    AdminService adminService;

    @Autowired
    SaltEntity saltEntity;

    @Autowired
    AdminJobRecordMapper adminJobRecordMapper;

    @Autowired
    StpInterfaceImpl stpInterface;

    @Autowired
    UserRoleService userRoleService;

    @PostMapping("/getKey")
    public ResponseUtil getKey() {
        try {
            // 获取公钥
            String publicKey = GenerateKey.cacheKey.get(GenerateKey.PUBLIC);
            String privateKey = GenerateKey.cacheKey.get(GenerateKey.PRIVATE);
            //签名
            HashMap<String, String> map = rsaUtil.RsaSign(publicKey, publicKey, privateKey);

            HashMap<String, String> hashMap = new HashMap<>(3);
            hashMap.putAll(map);
            hashMap.put("publicKey", publicKey);
            return ResponseUtil.setE(ResponseEnum.OK).setData(hashMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseUtil.setE(ResponseEnum.FAIL);
        }
    }

    @PostMapping("/start")
    public ResponseUtil start(@RequestBody String enCopyData) {
        // 获取密钥，解密密钥
        String publicKey = GenerateKey.cacheKey.get(GenerateKey.PUBLIC);
        String privateKey = GenerateKey.cacheKey.get(GenerateKey.PRIVATE);
        String deStr = rsaUtil.RsaPriDecrypt(enCopyData, publicKey, privateKey);
        if (deStr == null) return ResponseUtil.setE(ResponseEnum.LOGIN_INFO_ERROR);

        //验证身份信息
        LoginInfoEntity loginInfoEntity = JSON.parseObject(deStr, LoginInfoEntity.class);
        String handleSaltAccount = DigestUtil.md5Hex(loginInfoEntity.getAccount().concat(saltEntity.getAccount()));
        String handleSaltPassword = DigestUtil.md5Hex(loginInfoEntity.getPassword().concat(saltEntity.getPassword()));
        AdminEntity adminServiceById = adminService.getById(handleSaltAccount);
        if (ObjectUtil.isEmpty(adminServiceById)) return ResponseUtil.setE(ResponseEnum.LOGIN_INFO_ERROR);
        if (!adminServiceById.getPassword().equals(handleSaltPassword))
            return ResponseUtil.setE(ResponseEnum.LOGIN_INFO_ERROR);

        LambdaQueryWrapper<UserRoleEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserRoleEntity::getUserId, handleSaltAccount);
        UserRoleEntity userRoleEntity = userRoleService.getOne(lambdaQueryWrapper);
        if (!userRoleEntity.isEnabled()) return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("抱歉,你的账号已被封禁,请联系管理员.");

        // 验证是否在岗
        AdminJobRecordEntity jobRecordEntity = adminJobRecordMapper.queryOnGuardByAccount(handleSaltAccount);
        if (jobRecordEntity == null || jobRecordEntity.getOnGuard() == false)
            return ResponseUtil.setE(ResponseEnum.FAIL).setMsg("抱歉,您已离岗! 无法登录本系统.");


        //返回satoken，用户信息
        StpUtil.setStpLogic(new StpLogic("admin"));
        StpUtil.login(handleSaltAccount);
        stpInterface.getRoleList(handleSaltAccount, StpUtil.getLoginType());

        System.out.println("\033[32;4m" + "++++++++++++++++++++++++++++++" + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号" + handleSaltAccount + " 登录类型：" + StpUtil.getLoginType() + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号的角色集合：" + StpUtil.getRoleList() + "\033[0m");
        System.out.println("\033[32;4m" + "===>当前账号的权限码集合：" + StpUtil.getPermissionList() + "\033[0m");
        System.out.println("\033[32;4m" + "++++++++++++++++++++++++++++++" + "\033[0m");

        HashMap<String, String> result = new HashMap<>(2);
        result.put(StpUtil.getTokenName(), StpUtil.getTokenValue());
        HashMap entityConversionMap = JSONObject.parseObject(JSON.toJSONString(adminServiceById), HashMap.class);
        entityConversionMap.remove("account");
        entityConversionMap.remove("password");
        entityConversionMap.remove("registerTime");
        result.putAll(entityConversionMap);
        result.put("loginType", StpUtil.getLoginType());
        return ResponseUtil.setE(ResponseEnum.LOGIN_SUCCESS).setData(result);
    }

    @RequestMapping("/overdueVerify")
    public ResponseUtil overdueVerify() {
        return ResponseUtil.setE(ResponseEnum.LOGIN_VALID);
    }

    @GetMapping("/out")
    public ResponseUtil out() {
        StpUtil.logout();
        return ResponseUtil.setE(ResponseEnum.LOGIN_FAILURE);
    }
}
